package com.central.apps.handler.MaterialInventory;

import cn.hutool.core.util.IdUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.util.DateUtils;
import com.central.app.service.HandlerService;
import com.central.apps.common.util.DateUtiles;
import com.central.apps.service.IInventoryService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.bouncycastle.asn1.x500.style.RFC4519Style.o;

//入库单
@Slf4j
@Component
public class ReceiptDocHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        List<Map<String, Object>> bySql = handlerService.findBySql("select instonum from gq_instorage where id =" + id);
        String instonum = MapUtils.getString(bySql.get(0), "instonum");
        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_instoline where instonum='" + instonum + "'");

        if ("fqr".equals(flowNode.getId())){
            if (CollectionUtils.isEmpty(bySql1)){
                return "请添加物料行数据！";
            }
            List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_instorage where id=" + id);
           // String instonum = MapUtils.getString(bySql.get(0),"instonum");
            List<Map<String, Object>> bySql3 = handlerService.findBySql("SELECT * from biz_attribute where object_id=(SELECT id from biz_object where name ='gq_instoline') and required !=''");
            if (CollectionUtils.isNotEmpty(bySql3)){
                for(int i=0;i<bySql3.size();i++){
                    Map<String, Object> map = bySql3.get(i);
                    String required = MapUtils.getString(map, "required");
                    String id1 = MapUtils.getString(map, "id");
                    if (required!=null||required!=""){
                        String columnname = MapUtils.getString(bySql3.get(i), "columnname");
                        //校验子表必填，库位是库管员必填，发起人不必填
                        if("binnum".equals(columnname)){
                            continue;
                        }
                        List<Map<String, Object>> bySql4 = handlerService.findBySql("select "+columnname+" from gq_instoline where instonum='" + instonum + "'");
                        if (CollectionUtils.isNotEmpty(bySql4)){
                            Map<String, Object> map1 = bySql4.get(0);
                            String columnname1 = MapUtils.getString(map1, columnname);
                            log.info("o+++++++++++++++++++++++++++++++++++++" + o);
                            if (StringUtils.isEmpty(columnname1)){
                                log.info("required+++++++++++++++++++++++++++++++++++++" + columnname1);
                                return "物料行有必填信息未填，请继续填写!";
                            }else {
                                log.info("required+++++++++++++++++++++++++++++++++++++" + columnname1);
                            }
                        }
                    }
                }
            }
//            else if (CollectionUtils.isNotEmpty(bySql1)){
//                for (int i=0;i<bySql1.size();i++){
//                    Map<String, Object> map = bySql1.get(i);
//                    String conforaccept = MapUtils.getString(map, "conforaccept");
//                    if (!conforaccept.equals("是")){
//                        return "物料行中有不符合验收的物料！";
//                    }
//                }
//            }
        }else if("gly".equals(flowNode.getId())){
            //流程提交校验子表必填项
            return subTableRequire("gq_instoline", bySql1);

        }
        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    /**
     * 子表必填校验
     * @return
     */
    public String subTableRequire(String table,List<Map<String, Object>> list){
        String result = "";
        List<Map<String, Object>> bySql2 = handlerService.findBySql("SELECT columnname,description from biz_attribute where object_id=(SELECT id from biz_object where name ='"+table+"') and required !=''");
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);

            //遍历子表必填字段
            for (Map<String, Object> stringObjectMap : bySql2) {
                String columnname = MapUtils.getString(stringObjectMap, "columnname");
                String columnname1 = MapUtils.getString(map, columnname);
                if(StringUtils.isBlank(columnname1)){
                    result = "子表第"+(i+1)+"行，有必填字段未填写";
                    return result;
                }
            }
        }
        return result;
    }

//    @Override
//    public String validateFlowApproval(String app, Long id, FlowNode flowNode) throws Exception {
//        if ("fqr".equals(flowNode.getName())){
//            List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_instorage where id=" + id);
//            String instonum = MapUtils.getString(bySql.get(0),"instonum");
//            List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT * from biz_attribute where object_id=(SELECT id from biz_object where name ='gq_instoline')");
//            if (CollectionUtils.isNotEmpty(bySql1)){
//                for(int i=0;i<bySql1.size();i++){
//                    Map<String, Object> map = bySql1.get(i);
//                    String required = MapUtils.getString(map, "required");
//                    String id1 = MapUtils.getString(map, "id");
//                    if (required.equals("1")){
//                        String columnname = MapUtils.getString(map, "columnname");
//                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select '"+columnname+"' from gq_instoline where id='" + id1 + "'");
//                        if (CollectionUtils.isNotEmpty(bySql2)){
//
//                        }else {
//                            return "有必填信息未填，请继续填写!";
//                        }
//                    }
//                }
//            }
//        }
//        return super.validateFlowApproval(app, id, flowNode);
//    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if (flowNode.getId().equals("gly")){
            boolean flag = op.isFlag();
            if (flag){
                //查询接收入库主表gq_instorage
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_instorage where id=" + id);
                Map<String, Object> map = bySql.get(0);
                String instonum = MapUtils.getString(map, "instonum");
                String instodesc = MapUtils.getString(map, "instodesc");
                String status = MapUtils.getString(map, "status");
                String warehousenum = MapUtils.getString(map, "warehousenum");
                String storedesc = MapUtils.getString(map, "storedesc");
                String type = MapUtils.getString(map, "type");
                String createuserdesc = MapUtils.getString(map, "createuserdesc");
                String createuser = MapUtils.getString(map, "createuser");
                String deptcode = MapUtils.getString(map, "deptcode");
                String createtime = MapUtils.getString(map, "createtime");
                String subjectno = MapUtils.getString(map, "subjectno");
                String taskid1 = MapUtils.getString(map, "taskid");
                String proid1 = MapUtils.getString(map, "proid");
                String receiptnum = MapUtils.getString(map, "receiptnum");
                String recipientid = MapUtils.getString(map, "recipientid");
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_instoline where instonum ='" + instonum + "'");
                if (CollectionUtils.isNotEmpty(bySql1)){
                    for (int i=0;i<bySql1.size();i++) {
                        Map<String, Object> map1 = bySql1.get(i);
                        String itemnum = MapUtils.getString(map1, "itemnum");//物料编码
                        String itemdesc = MapUtils.getString(map1, "itemdesc");//物资描述
                        Float innum = MapUtils.getFloat(map1, "innum");//数量
                        //String poid = MapUtils.getString(map1, "poid");//订单行id
                        String linetype = MapUtils.getString(map1, "linetype");//物资类型
                        String model = MapUtils.getString(map1, "model");//规格型号
                        String orderunit = MapUtils.getString(map1, "orderunit");//订购单位
                        String unit = MapUtils.getString(map1, "unit");//发放单位
                        String converfactor = MapUtils.getString(map1, "converfactor");//转换系数
                        String brand = MapUtils.getString(map1, "brand");//品牌
                        String specifications = MapUtils.getString(map1, "specifications");//规格
                        String manufacturer = MapUtils.getString(map1, "manufacturer");//生产厂家
                        String batchnum = MapUtils.getString(map1, "batchnum");//批次
                        String manbanumber = MapUtils.getString(map1, "manbanumber");//厂商批次
                        String aactualdate = MapUtils.getString(map1, "aactualdate");//出厂日期
                        String binnum = MapUtils.getString(map1, "binnum");//货位
                        String occupnot = MapUtils.getString(map1, "occupnot");//是否专用
                        String storageroom = MapUtils.getString(map1, "storageroom");//库房
                        String linecost88 = MapUtils.getString(map1, "linecost");//行成本
                        String unitcost99 = MapUtils.getString(map1, "unitcost");//单位成本
                        BigDecimal linecost = new BigDecimal(linecost88);
                        BigDecimal unitcost = new BigDecimal(unitcost99);
                        String reqdeliverydate = MapUtils.getString(map1, "reqdeliverydate");//入库日期
                        String life = MapUtils.getString(map1, "life");//失效日期
                        String taskid = MapUtils.getString(map1, "taskid");//任务id
                        String proid = MapUtils.getString(map1, "proid");//项目id
                        List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_item where itemnum ='" + itemnum + "'");
                        if (CollectionUtils.isNotEmpty(bySql2)) {
                        Map<String, Object> map2 = bySql2.get(0);
                        Float standardcost = MapUtils.getFloat(map2, "standardcost");//标准成本
                        String packform = MapUtils.getString(map2, "packform");//封装形式
                        String maintechtors = MapUtils.getString(map2, "maintechtors");//主要技术指标
                        String qualitygrade = MapUtils.getString(map2, "qualitygrade");//质量等级
                        String lifemoney = MapUtils.getString(map2, "lifemoney");//寿命
                        //库存成本表，
                        List<Map<String, Object>> bySql3=null;
                            if (taskid1==null||taskid1==""){
                                bySql3 = handlerService.findBySql("select avgcost from gq_invcost where itemnum='" + itemnum + "'and storenum='" + warehousenum + "' and batchnum ='" + batchnum + "' and proid='" + proid1 + "' and subjectno='" + subjectno + "'");

                            }else {
                                bySql3 = handlerService.findBySql("select avgcost from gq_invcost where itemnum='" + itemnum + "'and storenum='" + warehousenum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid1 + "' and proid='" + proid1 + "' and subjectno='" + subjectno + "'");

                            }
                        if (CollectionUtils.isNotEmpty(bySql3)) {
                            //查询对应的库存余量表，获取余量
                            List<Map<String, Object>> bySql4=null;
                                if (taskid1==null||taskid1==""){
                                    bySql4= handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "'and storenum='" + warehousenum + "' and batchnum ='" + batchnum + "' and proid='" + proid1 + "' and binnum ='" + binnum + "' and subjectno='" + subjectno + "'");

                                }else {
                                    bySql4= handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "'and storenum='" + warehousenum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid1 + "' and proid='" + proid1 + "' and binnum ='" + binnum + "' and subjectno='" + subjectno + "'");

                                }
                            if (CollectionUtils.isNotEmpty(bySql4)) {
                                BigDecimal zong = new BigDecimal(0);
                                BigDecimal avg = new BigDecimal(0);
                                BigDecimal avgcost = new BigDecimal(0);
                                for (Map<String, Object> mapl : bySql4) {
                                    String curbal = MapUtils.getString(mapl, "curbal");
                                    BigDecimal bigDecimal = new BigDecimal(curbal);
                                    zong=zong.add(bigDecimal);
                                }
                                Map<String, Object> map3 = bySql3.get(0);
                                Float avgcost1 = MapUtils.getFloat(map3, "avgcost");
                                BigDecimal bigDecimal = new BigDecimal(avgcost1);
                                avg = bigDecimal;//库存平均价
                                BigDecimal bigDecimal1 = new BigDecimal(innum);
                                if ("接收".equals(type)) {

                                    avgcost=((bigDecimal1.multiply(unitcost)).add(zong.multiply(avg))).divide(bigDecimal1.add(zong));
                                    //avgcost = (innum * unitcost + zong * avg) / (innum + zong); //总的平均价格
                                } else {
                                    avgcost=((zong.multiply(avg)).subtract(bigDecimal1.multiply(unitcost))).divide(zong.subtract(bigDecimal1));
                                   // avgcost = (zong * avg - innum * unitcost) / (zong - innum);//总的平均价格
                                }
                                if (taskid1==null||taskid1==""){
                                    handlerService.updateBySql("update gq_invcost set avgcost= '" + avgcost + "',lastcost = '" + unitcost + "' where itemnum='" + itemnum + "'and storenum='" + warehousenum + "' and batchnum ='" + batchnum + "' and proid='" + proid1 + "' and subjectno='" + subjectno + "'");

                                }else {
                                    handlerService.updateBySql("update gq_invcost set avgcost= '" + avgcost + "',lastcost = '" + unitcost + "' where itemnum='" + itemnum + "'and storenum='" + warehousenum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid1 + "' and proid='" + proid1 + "' and subjectno='" + subjectno + "'");

                                }
                            }
                        } else {
                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("batchnum", batchnum);
                            hashMap.put("taskid", taskid1);
                            hashMap.put("proid", proid1);
                            hashMap.put("subjectno", subjectno);
                            hashMap.put("avgcost", unitcost);
                            hashMap.put("itemnum", itemnum);
                            hashMap.put("itemdesc", itemdesc);
                            hashMap.put("storenum", warehousenum);
                            hashMap.put("stdcost", standardcost);
                            hashMap.put("createuser", createuser);//创建人
                            hashMap.put("createuserdesc", createuserdesc);//创建人描述
                            hashMap.put("deptcode", deptcode);//创建人描述
                            handlerService.insert("gq_invcost", hashMap);
                        }
                        //更新库存
                        Map<String, Object> mapTory = new HashMap<>();
                        mapTory.put("itemnum", itemnum);//物料编码
                        mapTory.put("itemdesc", itemdesc);////物料名称
                        mapTory.put("itemtype", linetype);//物资类型
                        mapTory.put("storenum", warehousenum);//仓库编号
                        mapTory.put("storedesc", storedesc);//库房名称
                        mapTory.put("moneylife", lifemoney);//寿命
                        mapTory.put("model", model);//规格型号
                             mapTory.put("specifications",specifications);//规格
                        mapTory.put("spemodel", brand);//品牌
                        mapTory.put("manufacturer", manufacturer);//生产厂家
                        mapTory.put("packagform", packform);//封装形式
                        mapTory.put("orderunit", orderunit);//订购单位
                        mapTory.put("outunit", unit);//发放单位
                        mapTory.put("convercoe", converfactor);//转换系数
                        mapTory.put("maintechindicat", maintechtors);//主要技术指标
                        mapTory.put("quagrade", qualitygrade);//质量等级
                        mapTory.put("curbaltotal", innum);//库存余量
                        mapTory.put("avblbalance", innum);//可用余量
                        mapTory.put("createuser", createuser);//创建人
                        mapTory.put("createuserdesc", createuserdesc);//创建人描述
                        mapTory.put("deptcode", deptcode);//创建人描述
                        //插入库存余量
                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("itemnum", itemnum);
                        hashMap.put("storenum", warehousenum);
                        hashMap.put("itemdesc", itemdesc);
                        if (occupnot.equals("是")){
                            hashMap.put("applyby",recipientid);
                        }
                        // hashMap.put("ponum",ponum);
                        hashMap.put("unitcost", unitcost);
                        hashMap.put("binnum", binnum);
                        hashMap.put("batchnum", batchnum);
                        hashMap.put("manbanumber",manbanumber);
                        hashMap.put("aactualdate",aactualdate);
                        hashMap.put("taskid", taskid1);
                        hashMap.put("proid", proid1);
                        hashMap.put("orderunit",orderunit);
                        hashMap.put("subjectno", subjectno);
                        hashMap.put("receiptnum", "0");
                        hashMap.put("avblbalance", innum);
                        hashMap.put("curbal", innum);
                        String startdate =  DateUtiles.getYmdhms(new Date());
                        hashMap.put("startdate",startdate);//入库时间
                        hashMap.put("enddate", life);
                        if(StringUtils.isNotBlank(life)){
                            //根据失效日期和当前日期计算出失效天数
                            int enddays = handlerExpirationDays(life);
                            hashMap.put("enddays", enddays);
                        }

                        hashMap.put("createuser", createuser);//创建人
                            hashMap.put("createuserdesc", createuserdesc);//创建人描述
                            hashMap.put("deptcode", deptcode);//创建人描述
                        //查询库存主表，获取库存余量表 库 余量表这条数据查询，
                            List<Map<String, Object>> bySql4=null;
                            if (taskid1==null||taskid1==""){
                                bySql4 = handlerService.findBySql("select * from gq_invbalances where itemnum ='" + itemnum + "' and storenum ='" + warehousenum + "' and binnum ='" + binnum + "' and batchnum ='" + batchnum + "' and proid ='" + proid1 + "' and subjectno='" + subjectno + "'");

                            }else {
                                bySql4 = handlerService.findBySql("select * from gq_invbalances where itemnum ='" + itemnum + "' and storenum ='" + warehousenum + "' and binnum ='" + binnum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid1 + "' and proid ='" + proid1 + "' and subjectno='" + subjectno + "'");

                            }
                        if (CollectionUtils.isNotEmpty(bySql4)) {
                            //更新库存余量表
                            Map<String, Object> map3 = bySql4.get(0);
                            Float curbal = MapUtils.getFloat(map3, "curbal"); //当前余量
                            //Map<String, Object> map4 = bySql4.get(0);
                            Float avblbalance = MapUtils.getFloat(map3, "avblbalance");//可用余量
                            if ("接收".equals(type)) {
                                curbal = curbal + innum;
                                avblbalance = avblbalance + innum;
                            } else {
                                curbal = curbal - innum;
                                avblbalance = avblbalance - innum;
                            }
                            if (taskid1==null||taskid1==""){
                                handlerService.updateBySql("update gq_invbalances set curbal = '" + curbal + "',avblbalance = '" + avblbalance + "' where itemnum ='" + itemnum + "' and storenum ='" + warehousenum + "' and binnum ='" + binnum + "' and batchnum ='" + batchnum + "' and proid ='" + proid1 + "' and subjectno='" + subjectno + "'");

                            }else {
                                handlerService.updateBySql("update gq_invbalances set curbal = '" + curbal + "',avblbalance = '" + avblbalance + "' where itemnum ='" + itemnum + "' and storenum ='" + warehousenum + "' and binnum ='" + binnum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid1 + "' and proid ='" + proid1 + "' and subjectno='" + subjectno + "'");

                            }
                        } else {
                            //新增库存余量表信息
                            handlerService.insert("gq_invbalances", hashMap);
                        }
                        //查询库存主表信息
                        List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_inventory where  itemnum  ='" + itemnum + "'and storenum ='" + warehousenum + "'");
                        if (CollectionUtils.isNotEmpty(bySql5)) {
                            //库存余量表
                            List<Map<String, Object>> bySql6 = handlerService.findBySql("select * from gq_invbalances where  itemnum  ='" + itemnum + "'and storenum ='" + warehousenum + "'");
                            float curbal = 0;//库存余量
                            float avblbalance = 0;//可用余量
                            if (CollectionUtils.isNotEmpty(bySql6)) {
                                for (Map<String, Object> objectMap : bySql6) {
                                    Float curbal1 = MapUtils.getFloat(objectMap, "curbal");
                                    curbal = curbal + curbal1;//库存余量
                                    Float avblbalance1 = MapUtils.getFloat(objectMap, "avblbalance");
                                    avblbalance = avblbalance + avblbalance1;//库存可用余量
                                }
                                handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal + ", avblbalance = " + avblbalance + " where storenum = '" + warehousenum + "' and itemnum = '" + itemnum + "'");
                            }
                        } else {
                            handlerService.insert("gq_inventory", mapTory);
                        }
                            String instonumNew="";//入库编号
                            List<Map<String, Object>> bySql7 = handlerService.findBySql("SELECT instonum from gq_matusetrans where instonum  LIKE '%CDFI%' order by instonum desc limit 1");
                            if(CollectionUtils.isNotEmpty(bySql7)){
                                Map<String, Object> map7 = bySql7.get(0);
                                String instonum1 = MapUtils.getString(map7, "instonum");
                                int integer = Integer.valueOf(instonum1.substring(instonum1.length() - 8));
                                integer++;
                                instonumNew="CDFI"+integer;
                            }else{
                                instonumNew="CDFI10000001";
                            }                            //接收收据写下入到库存交易表中
//                        HashMap<String, Object> hashMap1 = new HashMap<>();
//                        hashMap1.put("instonum", instonumNew);
//                        hashMap1.put("instodesc", instodesc);
//                        hashMap1.put("itemnum", itemnum);
//                        hashMap1.put("itemdesc", itemdesc);
//                        hashMap1.put("storenum", warehousenum);
//                        hashMap1.put("storedesc", storedesc);
//                        hashMap1.put("unitcost", unitcost);
//                        hashMap1.put("linecost", linecost);
//                        hashMap1.put("lotnum", batchnum);
//                        hashMap1.put("taskid", taskid1);
//                        hashMap1.put("proid", proid1);
//                        hashMap1.put("unit", orderunit);
//                        hashMap1.put("binnum", binnum);
//                        //hashMap1.put("receiptnum",receiptnum);
//                        // hashMap1.put("ponum",ponum);
//                        hashMap1.put("createuserdesc", createuserdesc);
//                        hashMap1.put("createuser", createuser);
//                        hashMap1.put("deptcode", deptcode);
//                        hashMap1.put("createtime", new Date());
//                        hashMap1.put("status", status);
//                        hashMap1.put("quantity", innum);
//                        hashMap1.put("type", "接收");
//                        handlerService.insert("gq_matusetrans", hashMap1);
                            handlerService.updateBySql("insert into gq_matusetrans (subjectno,deptcode,instonum,instodesc,itemnum,itemdesc,quantity,unit,createtime,createuser,createuserdesc,storenum,storedesc,lotnum,type,unitcost,linecost,proid,taskid,binnum,status) values('"+subjectno+"','"+deptcode+"','"+instonumNew+"','"+instodesc+"','"+itemnum+"','"+itemdesc+"',"+innum+",'"+orderunit+"',now(),'"+createuser+"','"+createuserdesc+"','"+warehousenum+"','"+storedesc+"','"+batchnum+"','接收',"+unitcost+","+linecost+",'"+proid+"','"+taskid1+"','"+binnum+"','"+status+"')");
//                        if ("接收".equals(type)){
//                            List<Map<String, Object>> bySql6 = handlerService.findBySql("select orderqty,linecost from gq_poline where id ='" + poid + "'");
//                            Map<String, Object> map3 = bySql6.get(0);
//                            Float orderqty1 = MapUtils.getFloat(map3, "orderqty");
//                            Float linecost1 = MapUtils.getFloat(map3, "linecost");
//                            float orderqty = orderqty1 - innum;
//                            float linecost2 = linecost1 -linecost;
//                           handlerService.updateBySql("update gq_poline set orderqty ="+orderqty+",linecost ="+linecost2+" where id ='"+poid+"'");
//
//                        }
                    }
                    }
                }
            }
        }
        super.afterExcuteFlow(app, id, flowNode, op, event);
    }

    private int handlerExpirationDays(String life) {
        Date expirydate1 = DateUtils.getDate(life);
        Date currentDate = DateUtils.getCurrentDate();
        int day = DateUtils.daysBetween(currentDate,expirydate1);
        if(day < 0){
            day = 0;
        }
        return day;
    }


//    @Override
//    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
//        String idt = MapUtils.getString(params, "idt");
//        //查询接收入库主表gq_instorage
//        List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_instorage where id=" + idt);
//        Map<String, Object> map = bySql.get(0);
//        String instonum = MapUtils.getString(map, "instonum");
//        String instodesc = MapUtils.getString(map, "instodesc");
//        String status = MapUtils.getString(map, "status");
//        String types = MapUtils.getString(map, "type");
//        String receiptnum = MapUtils.getString(map, "receiptnum");
//        String createuserdesc = MapUtils.getString(map, "createuserdesc");
//        String createtime = MapUtils.getString(map, "createtime");
//        List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_instoline where instonum ='" + instonum + "'");
//        if (CollectionUtils.isNotEmpty(bySql1)){
//            for (int i=0;i<bySql1.size();i++){
//                Map<String, Object> map1 = bySql1.get(i);
//                String itemnum = MapUtils.getString(map1, "itemnum");//物料编码
//                String itemdesc = MapUtils.getString(map1, "itemdesc");//物资描述
//                Float innum = MapUtils.getFloat(map1, "innum");//数量
//                String batchnum = MapUtils.getString(map1, "batchnum");//批次
//                String binnum = MapUtils.getString(map1, "binnum");//货位
//                String storageroom = MapUtils.getString(map1, "storageroom");//库房
//                Float linecost = MapUtils.getFloat(map1, "linecost");//行成本
//                Float unitcost = MapUtils.getFloat(map1, "unitcost");//单位成本
//                String reqdeliverydate = MapUtils.getString(map1, "reqdeliverydate");//入库日期
//                String life = MapUtils.getString(map1, "life");//失效日期
//                String taskid = MapUtils.getString(map1, "taskid");//任务id
//                String proid = MapUtils.getString(map1, "proid");//项目id
//                List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_item where itemnum ='" + itemnum + "'");
//                Map<String, Object> map2 = bySql2.get(0);
//                Float standardcost = MapUtils.getFloat(map2, "standardcost");
//                //库存成本表，
//                List<Map<String, Object>> bySql3 = handlerService.findBySql("select avgcost from gq_invcost where itemnum='" + itemnum + "'and storenum='" + storageroom + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid + "' and proid='" + proid + "'");
//                if (CollectionUtils.isNotEmpty(bySql3)){
//                    //查询对应的库存余量表，获取余量
//                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_invbalances where itemnum='" + itemnum + "'and storenum='" + storageroom + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid + "' and proid='" + proid + "' and binnum ='" + binnum + "'");
//                    if (CollectionUtils.isNotEmpty(bySql4)){
//                        int zong = 0;
//                        float avg = 0;
//                        float avgcost = 0;
//                        for (Map<String,Object> mapl:bySql4){
//                            zong = +(int) mapl.get("curbal");
//                        }
//                        avg =(float) bySql3.get(0).get("avgcost");//库存平均价
//                        if ("接收".equals(types)){
//                            avgcost = (innum*unitcost + zong*avg)/(innum+zong); //总的平均价格
//                        }else {
//                            avgcost = (zong * avg - innum*unitcost)/(zong-innum);//总的平均价格
//                        }
//                        handlerService.updateBySql("update gq_invcost set avgcost= '" + avgcost + "',lastcost = '" + unitcost + "' where itemnum='" + itemnum + "'and storenum='" + storageroom + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid + "' and proid='" + proid + "'");
//                    }
//                }else {
//                    HashMap<String, Object> hashMap = new HashMap<>();
//                    hashMap.put("batchnum",batchnum);
//                    hashMap.put("taskid",taskid);
//                    hashMap.put("proid",proid);
//                    hashMap.put("avgcost",unitcost);
//                    hashMap.put("itemnum",itemnum);
//                    hashMap.put("storenum",storageroom);
//                    hashMap.put("stdcost",standardcost);
//                    handlerService.insert("gq_invcost",hashMap);
//                }
//                //更新库存
//                Map<String, Object> mapTory = new HashMap<>();
//                mapTory.put("itemnum",itemnum);//物料编码
//                mapTory.put("itemdesc",itemdesc);////物料名称
//                mapTory.put("storenum",storageroom);//仓库编号
//                mapTory.put("curbaltotal",innum);//库存余量
//                mapTory.put("avblbalance",innum);//可用余量
//                //插入库存余量
//                HashMap<String, Object> hashMap = new HashMap<>();
//                hashMap.put("itemnum",itemnum);
//                hashMap.put("storenum",storageroom);
//                hashMap.put("binnum",binnum);
//                hashMap.put("batchnum",batchnum);
//                hashMap.put("taskid",taskid);
//                hashMap.put("proid",proid);
//                hashMap.put("avblbalance",innum);
//                hashMap.put("curbal",innum);
//                hashMap.put("startdate",reqdeliverydate);
//                hashMap.put("enddate",life);
//                //查询库存主表，获取库存余量表 库 余量表这条数据查询，
//                List<Map<String, Object>> bySql4 = handlerService.findBySql("select * from gq_invbalances where itemnum ='" + itemnum + "' and storenum ='" + storageroom + "' and binnum ='" + binnum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid + "' and proid ='" + proid + "'");
//                if (CollectionUtils.isNotEmpty(bySql4)){
//                    //更新库存余量表
//                    float  curbal =(float) bySql4.get(0).get("curbal");//当前余量
//                    float avblbalance = (float) bySql4.get(0).get("avblbalance");//可用余量
//                    if ("接收".equals(types)){
//                        curbal = curbal + innum;
//                        avblbalance = avblbalance + innum;
//                    }else {
//                        curbal = curbal - innum;
//                        avblbalance = avblbalance - innum;
//                    }
//                    handlerService.updateBySql("update gq_invbalances set curbal = '" + curbal + "',avblbalance = '" + avblbalance + "' where itemnum ='" + itemnum + "' and storenum ='" + storageroom + "' and binnum ='" + binnum + "' and batchnum ='" + batchnum + "' and taskid ='" + taskid + "' and proid ='" + proid + "'");
//                }else {
//                    //新增库存余量表信息
//                    handlerService.insert("gq_invbalances", hashMap);
//                }
//                //查询库存主表信息
//                List<Map<String, Object>> bySql5 = handlerService.findBySql("select * from gq_inventory where  itemnum  ='" + itemnum + "'and storenum ='" + storageroom + "'");
//                if (CollectionUtils.isNotEmpty(bySql5)){
//                    //库存余量表
//                    List<Map<String, Object>> bySql6 = handlerService.findBySql("select * from gq_invbalances where  itemnum  ='" + itemnum + "'and storenum ='" + storageroom + "'");
//                    float curbal = 0;//库存余量
//                    float avblbalance = 0;//可用余量
//                    if (CollectionUtils.isNotEmpty(bySql6)){
//                        for (Map<String,Object> objectMap :bySql6){
//                            curbal = curbal+(float) objectMap.get("curbal");//库存余量
//                            avblbalance = avblbalance+(float) objectMap.get("avblbalance");//库存可用余量
//                        }
//                        handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal + ", avblbalance = " + avblbalance +  " where storenum = '" + storageroom + "' and itemnum = '" + itemnum + "'");
//                    }
//                }else {
//                    handlerService.insert("gq_inventory",mapTory);
//                }
//                //接收收据写下入到库存交易表中
//                HashMap<String, Object> hashMap1 = new HashMap<>();
//                hashMap1.put("instonum",instonum);
//                hashMap1.put("instodesc",instodesc);
//                hashMap1.put("itemnum",itemnum);
//                hashMap1.put("storenum",storageroom);
//                hashMap1.put("itemdesc",itemdesc);
//                hashMap1.put("receiptnum",receiptnum);
//                hashMap1.put("createuserdesc",createuserdesc);
//                hashMap1.put("createtime",createtime);
//                hashMap1.put("status",status);
//                hashMap1.put("type","接收");
//                handlerService.insert("gq_matusetrans",hashMap1);
//
//            }
//        }
//        return super.operate(app, type, params);
//    }

    /**
     * 入库申请针对物料行选择物料明细行。往库存台账里面库存余量里子表（关联子物料）插数据根据批次关联
     */
    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        /**
         * 1.拿到入库申请物料明细行的数据
         * 2.往库存台账关联子物料插数据
         */
        if("gq_materdetails".equals(objName)){
            String batchnum = MapUtils.getString(data, "batchnum");//批次
            String innum = MapUtils.getString(data, "innum");//数量
            String itemdesc = MapUtils.getString(data, "itemdesc");//物料描述
            String itemnum = MapUtils.getString(data, "itemnum");//物料编码
            String linetype = MapUtils.getString(data, "linetype");//物料类型
            String id = MapUtils.getString(data, "id");//入库申请里面成品半成品id
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("batchnum",batchnum);
            resultMap.put("innum",innum);
            resultMap.put("itemdesc",itemdesc);
            resultMap.put("itemnum",itemnum);
            resultMap.put("linetype",linetype);
            resultMap.put("reqdeliverydate",new Date());
            resultMap.put("materdetailsid",id);
            handlerService.insert("gq_submaterial",resultMap);
        }

    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("instorageApp".equals(app)){
                //存储uuid
                String instonum = MapUtils.getString(data, "instonum");
                List<Map<String, Object>> bySql = handlerService.findBySql("select * from gq_instoline where instonum='" + instonum + "'");
                if (CollectionUtils.isNotEmpty(bySql)){
                    for (int i=0;i<bySql.size();i++){
                        Map<String, Object> map = bySql.get(i);
                        String id = MapUtils.getString(map, "id");
                        String uid = IdUtil.simpleUUID();
                        handlerService.updateBySql("update gq_instoline set uuidprice='"+uid+"' where id='"+id+"'");
                    }
                }

        }
        super.beforSave(app, objName, data, isUpdate);
    }

    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        /**
         * 删除入库申请里面成品/半成品组成物料清单之前  删除库存台账里面库存余量里面的关联子物料数据
         * 1.根据
         */
        if("gq_materdetails".equals(objName)){
            //删除库存台账里面库存余量关联子物料数据
            handlerService.updateBySql("delete from gq_submaterial where materdetailsid = " + id);
        }
        super.beforDelete(app, objName, id, isLogic);
    }
}
